/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package niozeroclient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Teva
 */
public class NIOZeroClient 
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException 
    {
            String host = "localhost";
                    
            int port = 2000;
                                  
	    SocketAddress sad = new InetSocketAddress(host, port);
            
	    SocketChannel sc = SocketChannel.open();
            
	    sc.connect(sad);
            
	    sc.configureBlocking(true);

	   File file = new File("C:/JavaExample/file11.txt");
                          
           long start = System.currentTimeMillis();
            
           NIOZeroClient.fileTransfer(file, sc);
       
           System.out.println("Total time taken in MS--"+(System.currentTimeMillis() - start));
    }
    
     public static void fileTransfer(File in, SocketChannel sc) throws IOException 
    {
        
    ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 64 * 4);  
    
    FileChannel inChannel = new FileInputStream(in).getChannel();
      
    try 
    {
        long len;
        
        long position = 0;
        
        while((len = inChannel.read(buf)) != -1)
        {
            buf.flip();
            position += inChannel.transferTo(position, (int)buf.limit(), sc);
            buf.clear();
        }
     } 
    
    finally 
    {
        if (inChannel != null) 
        {
            inChannel.close();
        }        
    }
 
  }
}
